﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Web.WebView2.Core;

namespace noveldown
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void Button2_Click(object sender, EventArgs e)
        {
            try
            {
                WebView.Source = new Uri(TextBox1.Text);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "提示",MessageBoxButtons.OK,MessageBoxIcon.Warning);
            }
        }
        private void WebView_Click(object sender, EventArgs e)
        {
        }

        private void TabControl1_MouseClick(object sender, MouseEventArgs e)
        {
        }
        private string FormatHtml(string s)
        {
            s = s.Replace(@"\u003C", "<");
            s = s.Replace(@"\n", "\r\n");
            s = s.Replace(@"\""", "\"");
            return s.Substring(1, s.Length - 2);
        }
        private async void GetHtml()
        {
            var result = await WebView.CoreWebView2.ExecuteScriptAsync("document.body.outerHTML");
            TextBox2.Text = FormatHtml(result);
            if (Button1.Enabled)
                UpdateCatalogue();
            else
                DownloadContent();
        }
        private void DownloadContent()
        {
            Regex titleRegex = new Regex(">(.*?章.*?)<");
            string title = titleRegex.Match(TextBox2.Text).Groups[1].Value;
            TextBox3.AppendText("\r\n" + "标题：" + title);
            Regex contentRegex = new Regex(TextBox4.Text, RegexOptions.Singleline);
            string content = ContentFormat(contentRegex.Match(TextBox2.Text).Groups[1].Value);
            ;

            File.AppendAllText("小说.txt", title + "\r\n");
            File.AppendAllText("小说.txt", content + "\r\n" + "\r\n");
            DownloadPos += 1;
        }
        private string ContentFormat(string s)
        {
            s = s.Replace("<br />", "\r\n");
            s = s.Replace("<br>", "\r\n");
            s = s.Replace("<p>", "    ");
            s = s.Replace("</p>", "\r\n");
            s = Regex.Replace(s, "<.*?>", "");

            return s;
        }
        private string FindContent(string s)
        {
            // Dim maxLength As Long, maxStr As String = ""
            List<string> result = new List<string>();
            foreach (Match mtch in Regex.Matches(s, ">(.*?)<", RegexOptions.Singleline))
            {
                string text = mtch.Groups[1].Value;
                Debug.WriteLine(text);
                result.Add(text);
            }
            // Return maxStr
            // return Microsoft.VisualBasic.Strings.Join(result.ToArray(), "\r\n");
            return String.Join("\r\n", result);
        }

        private void UpdateCatalogue()
        {
            ListBox1.Items.Clear();
            //含什么什么章
            Regex regex = new Regex("<.*?章.*?>");
            foreach (Match mtch in regex.Matches(TextBox2.Text))
            {
                ListBox1.Items.Add(mtch.Value);

            }
            //含中文章节

            //纯数字章节序号

        }
         


        private void WebView_NavigationCompleted(object sender, CoreWebView2NavigationCompletedEventArgs e)
        {
            GetHtml();
        }

        private long _downloadPos = 0;
        private long DownloadPos
        {
            get
            {
                return _downloadPos;
            }
            set
            {
                _downloadPos = value;
                if (value < taskList.Count)
                {
                    TextBox3.Text = "第" + value + 1 + "/" + taskList.Count + "条，[" + taskList[(int)value] + "]下载中……";
                    WebView.Source = new Uri(new Uri(TextBox1.Text), taskList[(int)DownloadPos]);

                }
                else
                {
                    TextBox3.Text = "下载完毕！";
                    // string novelName = IInputBox("下载完毕！小说叫什么名字？", "保存小说");
                    string novelName = "test11";
                    if (File.Exists(novelName + ".txt"))
                        File.Delete(novelName + ".txt");
                    // FileSystem.Rename("小说.txt", novelName + ".txt");
                    Button1.Enabled = true;
                }
            }
        }
        /// <summary>
        ///  小说名称
        /// </summary>
        public string novelname { get; set; }

        public string author { get; set; }



        private List<string> taskList = new List<string>();

        private void Button1_Click(object sender, EventArgs e)
        {
            Button1.Enabled = false;
            taskList.Clear();
            Regex regex = new Regex("href=\"(.*?)\"");
            foreach (var obj in ListBox1.SelectedItems)
                taskList.Add(regex.Match(obj.ToString()).Groups[1].Value);

            TextBox3.Text = "目录" + taskList.Count + "条，开始逐条下载……";
            DownloadPos = 0;

        }

        
    }
}
